﻿using Microsoft.AspNetCore.Mvc;
using SageKing.AspNetCore.Controllers;
using SageKing.Database.Contracts;

namespace SageKing.OpenIddict.Resource.Contracts;

[ApiExplorerSettings(GroupName = "OpenIddictApi.CRUD")]
public abstract class CRUDResourceBaseController<TEntity, TKey> : OpenIddictApiBaseController, ICRUDBaseApi<TEntity, TKey>
     where TEntity : IEntityBaseId<TKey>, new()
{
    public readonly IBaseService<TEntity, TKey> Service;

    public CRUDResourceBaseController(IBaseService<TEntity, TKey> service)
    {
        Service = service;
    }

    [HttpPost]
    [Route("page")]
    public virtual async Task<SageKingResult<PageBase<TEntity>>> GetPageAsync([FromBody] PageBaseInput page)
    {
        var sageKingResult = new SageKingResult<PageBase<TEntity>>();

        var result = await Service.GetPageAsync(page);

        return sageKingResult.Ok(result);
    }

    [HttpGet("{id}")]
    public virtual async Task<SageKingResult<TEntity>> GetAsync(TKey id)
    {

        var sageKingResult = new SageKingResult<TEntity>();

        var result = await Service.GetDetail(id);
        if (result == null)
        {
            return sageKingResult.NotFound();
        }
        return sageKingResult.Ok(result);
    }

    [HttpPost]
    public virtual async Task<SageKingResult<TKey>> CreateAsync([FromBody] TEntity model)
    {
        var sageKingResult = new SageKingResult<TKey>();

        var result = await Service.AddReturnEntityAsync(model);

        return sageKingResult.Ok(result.Id);
    }

    [HttpPut]
    public virtual async Task<SageKingResult<bool>> UpdateAsync([FromBody] TEntity model)
    {
        await Service.Update(model);
        return new SageKingResult<bool>().Ok(true);
    }

    [HttpDelete("{id}")]
    public virtual async Task<SageKingResult<bool>> DeleteAsync(TKey id)
    {
        await Service.Delete(id);
        return new SageKingResult<bool>().Ok(true);
    }
}
